<template>
  <div></div>
</template>
<script setup lang="ts">
import {
  ref,
  onMounted,
  getCurrentInstance
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import { getDomain } from '@/api/login'
import { useRouter, useRoute } from "vue-router"
import useUserInfoStore from '@/store/userInfo';
// import bulletinDialog from '@/utils/bulletin.js'
import { bindWX, bindQW } from '@/api/user'
import { encryption } from "@/utils/util";
import { enCodeKey, client_id } from "@/const/const"
import { useHookI18n } from '@/hooks/i18n'
const { $t } = useHookI18n()
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const router = useRouter();
const route = useRoute();
const userStore = useUserInfoStore()
const emit = defineEmits([""])

const showTenant = ref(false)

const showType = ref('')

onMounted(() => {
  if (route.query) {
    let query = route.query
    query.loginType = 'weixin'
    if (query) {
      if (userStore.getters.access_token && query.back && query.back == 'bind') {
        showType.value = 'bind'
        let tp = {
          data: JSON.stringify(query)
        }
        let temp = encryption({
          data: tp,
          key: enCodeKey,
          param: ["data"]
        });
        let fun = null
        if (query.type == 'WECHAT_ENTERPRISE') {
          fun = bindQW
        } else {
          fun = bindWX
        }
        fun({ code: temp.data, appId: client_id }).then(res => {
          if (res.data.code != 0) {
            proxy.$notify({
              title: $t('message.prompt'),
              message: (res.data.msg),
              type: 'error',
              position: 'bottom-right'
            });
          }
          localStorage.setItem('bindRandom', '')
          router.push({
            path: '/userinfo'
          })
        }).catch(e => {
          router.push({
            path: '/userinfo'
          })
        })
      } else {
        showType.value = 'login'
        userStore.LoginByUsername(Object.assign({}, query)).then((data) => {
          localStorage.setItem('loginRandom', '')
          getTenantByUserList(data)
        }).catch(() => {
          router.push({ path: '/login' })
        })
      }
    }
  }
})
// 获取该用户下所有的租户列表
function getTenantByUserList(data: { userDto: { tenants: any[]; tenantId: any; tenant: any; }; }) {
  let list = []
  if (data.userDto && data.userDto.tenants) {
    list = data.userDto.tenants
    if (list.length > 0) {
      // 只有一个租户 或指定租户 直接进去
      if (list.length == 1 || (data.userDto.tenantId && data.userDto.tenant)) {
        userStore.setSwitchTenant(false)
        setUserInfoData(data)
      } else {
        userStore.setSwitchTenant(true)
        switchTenant(list)
      }
    }
  }
}
// 加入成功后写入数据
function setUserInfoData(data: { userDto: any; }) {
  if (data) {
    userStore.batchSetStore(data)
    userStore.setTenantId(data.userDto.tenantId)
    userStore.setTenantInfo(data.userDto.tenant)
    getDomainHandle()
  }
}
async function getDomainHandle() {
  await getDomain().then(res => {
    if (res.data && res.data.code == 0) {
      if (res.data.data) {
        if (res.data.data.systemName) {
          document.title = res.data.data.systemName
        }
        userStore.setTenantInfo(res.data.data)
        router.push({ path: '/index' });
      } else {
        // this.openLogin()
        router.push({ path: '/404' });
      }
    } else {
      // this.$router.push({ path: '/404' });
    }
  }).catch(err => {
    // this.$router.push({ path: '/404' });
  })
}
// 选择租户登录
function switchTenant(list: any[]) {
  let obj = {
    successClose: false,
    switchTenant: true,
    switchList: list,
    afterLogin: (dialog: { handleClose: () => void; }) => {
      // bulletinDialog.install()
      dialog.handleClose()
      router.push({ path: '/index' });
    }
  }
  showTenant.value = true
  proxy.$loginForm(obj)
}
</script>
